// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
	env: process.env.Env
})
const rp = require('request-promise');
const dateUtils = require('date-utils')
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
	switch (event.action) {
		case 'updateUserInfo': {
			return updateUserInfo(event)
		}
		case 'getUserInfo': {
			return getUserInfo(event)
		}
		default:
			break
	}
}

/**
 * 更新用户信息
 * @param {} event 
 */
async function updateUserInfo(event) {
	if(!event.openid){
		const wxContext = cloud.getWXContext();
		event.openid=wxContext.OPENID;
	}
	let res = await db.collection('mini_user').where({
		user_id: event.openid, // 填入当前用户 openid
	}).get();
	if (res.data.length > 0) {
		await db.collection('mini_user').where({
			user_id: event.openid
		}).update({
			data: {
				user_name: event.userInfo.nickName,
				user_cover: event.userInfo.avatarUrl,
				user_gender: event.userInfo.gender,
				user_province: event.userInfo.province,
				user_city: event.userInfo.city,
				user_country: event.userInfo.country,
			}
		})
	} else {
		await db.collection('mini_user').add({
			// data 字段表示需新增的 JSON 数据
			data: {
				user_id: event.openid,
				user_name: event.userInfo.nickName,
				user_cover: event.userInfo.avatarUrl,
				user_gender: event.userInfo.gender,
				user_province: event.userInfo.province,
				user_city: event.userInfo.city,
				user_country: event.userInfo.country,
				timestamp: Date.now()
			}
		})
	}
	let result =await getUserInfo(event);
	return result;
}
/**
 * 获取用户信息
 * @param {} event 
 */
async function getUserInfo(event) {
	if(!event.openid){
		const wxContext = cloud.getWXContext();
		event.openid=wxContext.OPENID;
	}
	let result =await db.collection('mini_user').where({
		user_id: event.openid // 填入当前用户 openid
	}).get();
	return result;
}